const express = require('express');
const { Course, Membership, User, Order } = require('../models');
const { NotFound, BadRequest } = require('http-errors');
const { failure, success } = require('../utils/responses');
const { getKey, setKey } = require('../utils/redis');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const {broadcastOrderCount} = require('../streams/count-order')

const op = {
  attributes: { exclude: ['id', 'UserId'] },
  include: [
    {
      model: User,
      as: 'user',
      attributes: ['id', 'username', 'avatar'],
    },
  ],
};

/* 
查询用户订单
GET /orders */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      ...op,
      where: { userId: req.userId },
      order: [['id', 'desc']],
      limit: pageSize,
      offset,
    };
    if (query.outTradeNo) {
      condition.where.outTradeNo = query.outTradeNo;
    }
    if (query.tradeNo) {
      condition.where.tradeNo = query.tradeNo;
    }
    if (query.status) {
      condition.where.status = query.status;
    }

    const { count, rows } = await Order.findAndCountAll(condition);
    success(res, '查询成功', {
      orders: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 统计初始订单数据
 * */ 

// router.get('/order', async(req, res) => {
//     try {

//     } catch (error) {
//         failure(res, error)
//     }
// })

/**
 * 创建订单
 * */
router.post('/', async function (req, res) {
  try {
    const outTradeNo = uuidv4().replace(/-/g, '');
    const membership = await getMembership(req);
    const order = await Order.create({
      outTradeNo: outTradeNo,
      userId: req.userId,
      subject: membership.name,
      totalAmount: membership.price,
      membershipMonths: membership.durationMonths,
      status: 0,
    });
    await broadcastOrderCount()
    success(res, '订单创建成功', { order });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 查询大会员信息
 * @param req
 * @returns {Promise<*>}
 * */

async function getMembership(req) {
  const { membershipId } = req.body;
  if (!membershipId) {
    throw new BadRequest('请选择要购买的大会员');
  }
  let membership = await getKey(`membership:${membershipId}`);
  if (!membership) {
    membership = await Membership.findByPk(membershipId);
    if (!membership) {
      throw new NotFound('未查询到大会员');
    }
    await setKey(`membership:${membershipId}`, membership);
  }
  return membership;
}

/* 
查询用户订单详情
GET /orders */
router.get('/:outTradeNo', async function (req, res) {
  try {
    const order = await getOrder(req);
    success(res, '查询成功', { order });
  } catch (error) {
    failure(res, error);
  }
});

const getOrder = async (req) => {
  const { outTradeNo } = req.params;
  const order = await Order.findOne({
    ...op,
    where: {
      outTradeNo,
      userId: req.userId, // 用户只能查看自己的订单
    },
  });

  if (!order) {
    throw new NotFound(`订单: ${outTradeNo} 的订单未找到`);
  }

  return order;
};

module.exports = router;
